package com.zhang.sql;

import com.zhang.second.utils.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @title: 查询注册的表
 * @author: zhang
 * @date: 2022/2/10 21:57
 */
public class StreamToSqlAgg {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //
        SingleOutputStreamOperator<SensorReading> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return new SensorReading(
                                fields[0], Integer.parseInt(fields[1])
                        );
                    }
                });

        // todo 将流进行表注册
        tableEnv.createTemporaryView("sensor", sensorDS);

        // todo 使用sql查询注册的表

        Table sqlQuery = tableEnv.sqlQuery("select sensorId,sum(temperature) ct from sensor group by sensorId");

        //todo 将表对象转换为流进行打印输出
        //tableEnv.toChangelogStream(sqlQuery).print();

        env.execute();
    }
}
